package com.wzz.seckillone.activeMq.base;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.alter.AlterExpression;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @ProjectName: seckillOne
 * @Package: com.wzz.seckillone.activeMq
 * @ClassName: TopicConsumer
 * @Author: wzz
 * @Description: 消息消费者
 * @Date: 2022/3/20 14:50
 * @Version: 1.0
 */
@Slf4j
public class TopicConsumer {
    private static final String ACTIVEMQ_URL = "tcp://192.168.1.104:61616";
    private static final String topicName = "topicOne";
    public static void main(String[] args) throws JMSException {
        System.out.println("******z3");
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        Connection connection = connectionFactory.createConnection();
        connection.setClientID("***张三订阅");

        Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
        Topic topic = session.createTopic(topicName);
        TopicSubscriber subscriber = session.createDurableSubscriber(topic, "remark****");
        connection.start();
        /*
        *持久化的主题发送  一定要先运行消费者（等于先订阅），然后在运行消息生产者发送消息 ，无论消费者在不在线 都会收到消息
        *
        * */
        Message receive = subscriber.receive();

        try{
            while(receive != null){
                TextMessage textMessage = (TextMessage) receive;
                System.out.println(textMessage.getText());
                receive = subscriber.receive(1000l);
            }
            session.commit();//如果不手动提交事务  会重复消费
        }catch (Exception e){
            session.rollback();
            log.info(e.getMessage());
        }finally {
            subscriber.close();
            session.close();
            connection.close();
        }



    }
}
